const fs = require('fs');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
const ApiError = require('../utils/ApiError');

// 提交数据路径
const SUBMISSIONS_PATH = path.resolve(__dirname, '../data/submissions.json');

// 初始化提交数据
const initializeSubmissions = () => {
    if (!fs.existsSync(SUBMISSIONS_PATH)) {
        fs.writeFileSync(SUBMISSIONS_PATH, JSON.stringify([], null, 2));
    }
};

// 获取所有提交记录
const getAllSubmissions = async () => {
    initializeSubmissions();
    return new Promise((resolve, reject) => {
        fs.readFile(SUBMISSIONS_PATH, 'utf8', (err, data) => {
            if (err) {
                console.error('读取提交文件失败:', err);
                return reject(new ApiError(500, '读取提交数据失败'));
            }
            try {
                resolve(JSON.parse(data));
            } catch (parseErr) {
                console.error('解析提交数据失败:', parseErr);
                reject(new ApiError(500, '解析提交数据失败'));
            }
        });
    });
};

// 保存所有提交记录
const saveAllSubmissions = async (submissions) => {
    return new Promise((resolve, reject) => {
        fs.writeFile(SUBMISSIONS_PATH, JSON.stringify(submissions, null, 2), (err) => {
            if (err) {
                console.error('保存提交文件失败:', err);
                reject(new ApiError(500, '保存提交数据失败'));
            } else {
                resolve();
            }
        });
    });
};

// 创建提交记录
exports.createSubmission = async (submissionData) => {
    try {
        const submissions = await getAllSubmissions();
        const newSubmission = {
            id: uuidv4(),
            ...submissionData,
            submittedAt: new Date().toISOString(),
            status: 'submitted'
        };
        
        submissions.push(newSubmission);
        await saveAllSubmissions(submissions);
        return newSubmission;
    } catch (err) {
        console.error('创建提交记录失败:', err);
        throw new ApiError(500, '创建提交记录失败');
    }
};

// 获取学生的所有提交
exports.getSubmissionsByStudentId = async (studentId) => {
    try {
        const submissions = await getAllSubmissions();
        return submissions.filter(sub => sub.studentId === studentId);
    } catch (err) {
        console.error('获取学生提交记录失败:', err);
        throw new ApiError(500, '获取学生提交记录失败');
    }
};

// 通过ID获取提交
exports.getSubmissionById = async (id) => {
    try {
        const submissions = await getAllSubmissions();
        const submission = submissions.find(sub => sub.id === id);
        
        if (!submission) {
            throw new ApiError(404, '提交记录未找到');
        }
        
        return submission;
    } catch (err) {
        console.error('获取提交记录失败:', err);
        throw err;
    }
};

// 评分提交
exports.gradeSubmission = async (id, grade, feedback = '') => {
    try {
        const submissions = await getAllSubmissions();
        const index = submissions.findIndex(sub => sub.id === id);
        
        if (index === -1) {
            throw new ApiError(404, '提交记录未找到');
        }
        
        submissions[index] = {
            ...submissions[index],
            grade,
            feedback,
            status: 'graded',
            gradedAt: new Date().toISOString()
        };
        
        await saveAllSubmissions(submissions);
        return submissions[index];
    } catch (err) {
        console.error('评分提交失败:', err);
        throw err;
    }
};

// 获取实验的所有提交
exports.getSubmissionsByExperimentId = async (experimentId) => {
    try {
        const submissions = await getAllSubmissions();
        return submissions.filter(sub => sub.experimentId === experimentId);
    } catch (err) {
        console.error('获取实验提交记录失败:', err);
        throw new ApiError(500, '获取实验提交记录失败');
    }
};